import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// 引入接口
import { loginAPI, logoutAPI, userinfoAPI } from '@api/user/index'
// 引入数据类型
import type { loginForm, loginDataType, userResponseData } from '@api/user/type.ts'
import type { UserInfoState } from './types/type.ts'
// 引入消息组件
import { ElNotification } from 'element-plus'
// 引入类型
import { getTime } from '@/utils/time'
// 引入路由
import { constantRoute } from '@/router/routes'
import type { RouteRecordRaw } from "vue-router";

export const useLoginStore = defineStore('login', () => {
  const token = ref<string>('') // token
  const userinfo = ref<UserInfoState>({}) // 用户信息
  const router = useRouter()
  const route = useRoute()
  const menuRoute = ref<RouteRecordRaw[]>([]) // 仓库存菜单

  // 登录
  const userLogin = async (data: loginForm) => {
    const res: loginDataType = await loginAPI(data)

    if (res.code === 200) {
      // 登录成功，保存token
      token.value = (res.data as string)
      menuRoute.value = constantRoute
      // 登录成功后判断路径是否有路径参数，有就跳转对应页面，没有就跳转首页
      getUserInfo()

      setTimeout(() => {
        router.push({ path: (route.query.redirect as string) || '/' })
      }, 1000)
      ElNotification({
        message: '欢迎回来',
        type: 'success',
        title: getTime()
      })
    } else {
      // 登录失败，返回失败状态
      ElNotification({
        message: res.data,
        type: 'error',
      })
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    const res: userResponseData = await userinfoAPI()
    userinfo.value = res.data
  }

  // 退出登录
  const userLogout = () => {
    logoutAPI().then(res => {
      if (res.code === 200) {
        token.value = ''
        userinfo.value = {}
        router.push({ path: '/login', query: { redirect: route.path } })
      } else {
        // 退出登录失败，返回失败状态
        ElNotification({
          message: res.data,
          type: 'error',
        })
      }
    })
  }

  return { token, userLogin, menuRoute, userinfo, getUserInfo, userLogout }
}, {
  persist: true
})